﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Discovery;
using System.Text;
using EnOcean;
using ServiceContract;

namespace EnOceanReceiver
{
  [ServiceBehavior(Name = "EnOceanReceiver", Namespace = "http://enoceannet.codeplex.com/EnOceanReceiver/v1", InstanceContextMode = InstanceContextMode.Single)]
  public class Receiver : IEnOceanReceiver
  {
    private ServiceHost host;
    private IEnumerable<long> subscriptions;

    public Receiver(IEnumerable<long> subscriptions)
    {
      Uri address;
      ServiceDiscoveryBehavior sdb;

      this.subscriptions = subscriptions;

      address = new Uri("http://" + Dns.GetHostName() + "/EnOceanReceiver/" + Guid.NewGuid().ToString());

      host = new ServiceHost(this);
      host.AddServiceEndpoint(typeof(IEnOceanReceiver), new BasicHttpBinding() { Namespace = "http://enoceannet.codeplex.com/EnOceanReceiver/v1" }, address);
      host.AddServiceEndpoint(new UdpDiscoveryEndpoint() { IsSystemEndpoint = true });

      sdb = new ServiceDiscoveryBehavior();
      sdb.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint() { IsSystemEndpoint = true });

      host.Description.Behaviors.Add(sdb);
    }

    /// <summary>
    /// The event fires when a message is received from the transiever.
    /// </summary>
    public event EventHandler<TelegramReceivedEventArgs> TelegramReceived = delegate { };

    public void Stop()
    {
      host.Close();
    }

    public IEnumerable<long> Subscriptions()
    {
      Console.WriteLine("Subscriptions");
      return this.subscriptions;
    }

    public void SensorUpdated(SensorData sensorData)
    {
      Telegram t;

      if (sensorData.SensorId != 0)
      {
        t = Telegram.Parse(sensorData.EnOceanTelegram);
        TelegramReceived(this, new TelegramReceivedEventArgs(t, sensorData.Timestamp));
      }
    }

    public void Start()
    {
      host.Open();
    }
  }
}
